{{right_sidebar_enabled=True}}
{{extend 'layout.html'}}

{{=H5(video.title)}}
{{=A(T("Show video"),
     _href=URL(f="show",
               args=["video", video.id]))}}
({{=T("Remember to save changes first!")}}) / 
{{=A(T("Edit slides"), _href=URL(f="slides",
                                 args=["video", video.id]))}}
{{if subtitulation:}}
  / {{=A(T("Import subtitles"),
         _href=URL(f="srt",
                   args=["do", "import", "which", subtitulation]))}}
  / {{=A(T("Export subtitles"),
           _href=URL(f="srt",
           args=["do", "export", "which", subtitulation]))}}
{{pass}}

{{=FORM(DIV(INPUT(_type="button", _value=T("Back"),
                  _id="step_back"),
             INPUT(_type="button", _value=T("Pause/Play"),
                   _id="pause_play"),
             INPUT(_type="button", _value=T("Forward"),
                   _id="step_forward")),
        DIV(LABEL(T("Step (seconds)")),
                  INPUT(_type="text", _value=3, _id="step_value")))}}

{{if video.service=="youtube":}}
  {{=DIV(_id="video", _class="subtitles")}}
  {{pop='Popcorn.youtube("%(id)s", "http://www.youtube.com/watch?v=%(code)s");' % \
dict(id="video", code=video.code)}}
{{else:}}
  {{=DIV(VIDEO(*[SOURCE(_src=source.url) for source in sources],
               _id="ourvideo"),
         _id="video", _class="subtitles")}}
  {{pop='Popcorn("#ourvideo");'}}
{{pass}}

{{=SCRIPT("""
jQuery(document).ready(function(){

function getSubtitle(id){
  var theSubtitle = null
  jQuery.each(ourSubtitles,
              function(i, obj){if(Number(obj.id) == Number(id)){
                                theSubtitle = obj;
                                return;}
                                });
  return theSubtitle;
}

function fillSubtitleForm(id){
  var theSubtitle = getSubtitle(id);
  jQuery("[name=body]").val(theSubtitle.body);
  jQuery("[name=starts]").val(theSubtitle.starts);
  jQuery("[name=ends]").val(theSubtitle.ends);  
}

function toggleSubtitle(id){
  fillSubtitleForm(id);
  jQuery("select#subtitles option").attr("selected", false);
  jQuery("select#subtitles option[value=" + id + "]").attr("selected", true);
}

function timeToSeconds(timeStr){
  var seconds = Number(timeStr.slice(0, 2))*3600
  seconds += Number(timeStr.slice(3, 5))*60
  seconds += Number(timeStr.slice(6, 8));
  return Number(seconds);}

function toggleByTime(){
  var subtitleTime = Number(pop.currentTime());
  jQuery.each(ourSubtitles,
              function (i, obj){
                var starts = timeToSeconds(obj.starts);
                var ends = timeToSeconds(obj.ends);
                if ((starts <= subtitleTime) && (ends >= subtitleTime)){
                  currentSubtitle = obj;
                  toggleSubtitle(obj.id);
                  return;
                }
              });
}

function clickSubtitle(){
  if(!holDown){
    currentSubtitle = getSubtitle(this.value);
    toggleSubtitle(this.value);
    setSubtitleTime(this.value);
  }
}

function insertCallback(data){
  // Append the new subtitle to the object list
  // and register it in popcorn
  ourSubtitles.push(data.subtitle);
  jQuery("#subtitles").append(data.option);
  toggleSubtitle(data.subtitle.id);
  addCue(data.subtitle);
  jQuery("#subtitles [value=" + data.subtitle.id + "]").click(clickSubtitle);
}

function insertSubtitle(){
  // Request a new subtitle
  var url = "%(url)s" + "/create?";
  url += "subtitulation_id=%(subtitulation)s";
  url += "&starts=" + pop.currentTime();
  url += "&ends=" + (pop.currentTime() + Number(%(timeout)s));
  jQuery.get(url, insertCallback);
}

function removeSubtitle(){
// Remove current selected subtitles
try{
    // remove from list
    jQuery("select#subtitles option:selected").each(function(i, obj){
      jQuery("option[value=" + obj.value + "]").remove();
      // remove from db
      jQuery.get("%(url)s" + "/delete?id=" + obj.value);
      // Reset the cue event
      removeCue(getSubtitle(obj.value));
      // remove from array
      var index = null;
      jQuery.each(ourSubtitles, function(i, obj2){if(obj2.id == obj.value){
                                                 index = i;
                                                 return;}
      });
      if (index) {
                  ourSubtitles.splice(index, 1)}
      }
    );
  }
catch(e){
  // BUG: choosing the first subtitle triggers an addCue
  // call that  sets currentSubtitle to null
  // so it is not possible to remove the db record.
}
}

function changeSubtitle(){
  // Get subtitle object
  var myId = jQuery("#subtitles option:selected").val();
  if(myId){
    // console.log("Current subtitle as reference is " + currentSubtitle.id);
    var subtitle = getSubtitle(myId);
  }
  else{
    // console.log("Aborting change: no subtitle reference was selected");
    return null;
  }

  // Get form values
  subtitle.starts = jQuery("[name=starts]").val();
  subtitle.ends = jQuery("[name=ends]").val();
  subtitle.body = jQuery("[name=body]").val();

  // Update option
  var mySelector = "option[value=" + subtitle.id + "]";
  jQuery(mySelector).text(subtitle.starts + " - " + subtitle.ends);

  // Cancel cues
  removeCue(subtitle);
  // Add new cues
  addCue(subtitle);
  return myId
}

function applySubtitles(){
  var changed = changeSubtitle();
  if(changed != null){
    submitSubtitles(changed);
  }
  else{
    // console.log("No subtitle reference");
  }
}

function applyAll(){
  submitSubtitles();
}

function submitSubtitlesCallback(data, text, jq){
  // Server response on subtitle update
}

function submitSubtitles(id){
  if (id){
    var payload = getSubtitle(id);
  }
  else {var payload = ourSubtitles;}
  jQuery.post("%(url)s" + "/update",
              {data: JSON.stringify(payload)},
              submitSubtitlesCallback);
}

function stepForward(){
  var newTime = Number(jQuery("#step_value").val())+Number(pop.currentTime());
  pop.currentTime(newTime);
  toggleByTime();
}

function stepBack(){
  var newTime = Number(pop.currentTime())-Number(jQuery("#step_value").val());
  pop.currentTime(newTime);
  toggleByTime();
}

function pausePlay(){
  if (pop.paused()){
    pop.play();
  }
  else{
    pop.pause();
  }
}

function setSubtitleTime(id){
  var tmpSubtitle = getSubtitle(id);
  var newTime = timeToSeconds(tmpSubtitle.starts);
  pop.currentTime(newTime);
}

function doNothing(){
  // Do nothing
}

function sameCue(obj){
  var result = false;
  jQuery.each(ourSubtitles, function(i, obj2){
                              if(obj.ends == obj2.starts){
                                result = true;
                                // console.log("Found a starts-ends conflict between " + obj.id + " and " + obj2.id);
                                return;
                              }
                            });
  return result;
}

function addCue(obj){
  // console.log("Adding a starting cue for subtitle " + obj.id);
  pop.cue(obj.starts,
          function(){
                     // console.log("Cue " + obj.id + " has started");
                     currentSubtitle = obj;
                     toggleSubtitle(obj.id);
                    });
  obj.startEvent = pop.getLastTrackEventId();
  // console.log("Adding a starting cue for subtitle " + obj.id);
  pop.cue(obj.ends,
          function(){
                     // console.log("Cue " + obj.id + " has ended");
                     // Don't reset current subtitle if there is
                     // another with the same cue time
                     if(sameCue(obj)){
                       currentSubtitle = null;
                     }
                     else{
                       // console.log("Preserving currentSubtitle value");
                     }
          });
  obj.endEvent = pop.getLastTrackEventId();
}

function removeCue(obj){
  pop.cue(obj.startEvent, doNothing);
  pop.cue(obj.endEvent, doNothing);
}

var holDown = false;
var pop = %(pop)s;
var ourSubtitles = %(subtitles)s;
var currentSubtitle = null;

jQuery("select#subtitles option").click(clickSubtitle);
jQuery("select#subtitles").change(clickSubtitle);
jQuery("input#apply").click(applySubtitles);
jQuery("#step_forward").click(stepForward);
jQuery("#step_back").click(stepBack);
jQuery("#pause_play").click(pausePlay);
jQuery("#subtitle_insert").click(insertSubtitle);
jQuery("#subtitle_remove").click(removeSubtitle);
jQuery("#subtitle_apply").click(applyAll);
jQuery(ourSubtitles).each(function(i, obj){
                       addCue(obj);
                     });
jQuery("[name=body]").change(changeSubtitle);
jQuery("[name=starts]").change(changeSubtitle);
jQuery("[name=ends]").change(changeSubtitle);

jQuery(document).keydown(function(e){if(e.ctrlKey){holDown = true;} });
jQuery(document).keyup(function(e){if(e.ctrlKey){holDown = false;} });

});""" % dict(subtitles=subtitles.json(), subtitulation=subtitulation, 
              url=URL(f="subtitle.json", args=["subtitle",]),
              timeout=session.options["timeout"], pop=pop),
              _type="text/javascript")}}

{{block right_sidebar}}
{{=H5(T("Subtitles for %s language") % 
      session.options["language"])}}
{{=FORM(INPUT(_type="button", _value=T("Remove"),
              _id="subtitle_remove"),
        INPUT(_type="button", _value=T("Insert"),
              _id="subtitle_insert"),
        INPUT(_type="button", _value=T("Apply all changes"),
              _id="subtitle_apply"))}}

{{=SELECT(*[OPTION("%(starts)s - %(ends)s" % dict(starts=sub.starts,
                                                  ends=sub.ends),
                                                  _value=sub.id) \
for sub in subtitles], _multiple="multiple", _id="subtitles")}}

{{=ioform.custom.begin}}

{{ioform.custom.widget.body.attributes["_rows"] = 1}}

{{=LABEL(T("Edit subtitle"))}}{{=BR()}}
{{=ioform.custom.widget.body}}{{=BR()}}
{{=LABEL(T("Starts"))}}{{=BR()}}
{{=ioform.custom.widget.starts}}{{=BR()}}
{{=LABEL(T("Ends"))}}{{=BR()}}
{{=ioform.custom.widget.ends}}{{=BR()}}
{{=ioform.custom.end}}{{=BR()}}
{{=INPUT(_type="button", _value=T("Apply"),
              _id="apply")}}

{{end}}
